<template>
  <div class="app-container">
    <el-tabs type="border-card">
      <el-tab-pane label="设计">
        <el-row>
          <el-col :span="24">
            <el-form :inline="true">
              <el-form-item>
                <el-button-group>
                  <el-button
                    type="primary"
                    @click="onOpenTable(true)"
                  >加载Table</el-button>
                  <!-- <el-button
                    type="primary"
                    @click="onOpenTable()"
                  >选择Table</el-button> -->
                  <el-button
                    type="primary"
                    @click="onPreviewClick()"
                  >预览代码</el-button>
                  <el-button
                    type="primary"
                    @click="onExportClick()"
                  >下载代码</el-button>
                </el-button-group>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form :inline="true">
              <el-form-item>
                <el-button
                  v-if="sTables[0]"
                  type="primary"
                  @click="onExportsClick()"
                >已选需下载代码的表</el-button>
                <span
                  v-for="(item, index) in sTables"
                  :key="index"
                ><a @click="onRemoveClick(index)">
                    {{ index==0?item.name:', '+item.name }}
                  </a>
                </span>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-table
          :data="table.columns"
          row-key="id"
          border
          highlight-current-row
        >
          <el-table-column
            label="Name"
            prop="name"
          />
          <el-table-column
            label="Comment"
            prop="comment"
          />

          <el-table-column
            label="Property Type"
            prop="propertyType"
          />
          <el-table-column
            label="form Type"
            prop="formType"
          />
          <el-table-column
            label="Length"
            prop="lenght"
          />

        </el-table>
      </el-tab-pane>
      <el-tab-pane
        v-for="(item, index) in templates"
        :key="index"
        :label="item.name"
      >
        <el-row>
          <el-col :span="24">
            <el-button @click="handleCopy(item.format,$event)">Copy</el-button>
          </el-col>
        </el-row>
        <template>
          <pre>{{ item.format }}</pre>
        </template>
      </el-tab-pane>
    </el-tabs>

    <el-dialog
      :visible.sync="tableDialogVisible"
      title="选择表"
    >
      <el-table
        :data="tables"
        border
        highlight-current-row
        height="600"
      >
        <el-table-column label="表名称">
          <template slot-scope="scope">
            <a
              href="#"
              @click="onSelectTable(scope.row)"
            >{{ scope.row.name }}</a>
          </template>
        </el-table-column>
        <el-table-column
          property="comment"
          label="表注释"
        />
      </el-table>
    </el-dialog>

    <el-dialog :visible.sync="previewDialogVisible">
      <div
        slot="title"
        class="header-title"
      >
        <span style="font-size: 26px;">[{{ table.name || '空' }}] 生成代码参数</span>
      </div>
      <el-form
        label-position="right"
        label-width="160px"
      >
        <el-form-item label="模块名">
          <el-input
            v-model="table.moduleName"
            @change="onModuleChange()"
          />
        </el-form-item>
        <el-form-item label="API Path">
          <el-input v-model="table.requestPath" />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="onPreviewDialogCancel()">取 消</el-button>
        <el-button
          type="primary"
          @click="onPreviewDialogConfirm()"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import * as CodeDesignApi from '@/api/codedesign'
import axios from 'axios'

import clip from '@/utils/clipboard'
import clipboard from '@/directive/clipboard/index.js'

export default {
  directives: [clipboard],
  filters: {
    booleanFilter(val) {
      return val === true ? '是' : '否'
    }
  },
  data() {
    return {
      sTables: [],
      templates: [],
      table: {},
      tables: [],
      query: {},
      tableDialogVisible: false,
      previewDialogVisible: false,
      reload: false,
      day: ''
    }
  },
  created() { },
  mounted() {
  },
  methods: {
    onPreviewDialogConfirm() {
      this.previewDialogVisible = false
      // 预览代码
      // CodeDesignApi.previewCode(this.table).then(response => {
      //   this.templates = response.data.templates || []
      // })
      const actionUrl = this.HOST + '/codedesign' + '/previewCode'
      axios({
        url: actionUrl,
        method: 'post',
        params: { paperId: 1 }
      }).then(response => {
        console.log('response')
        console.log(response)
        this.templates = response.data.templates || []
      })
    },
    onPreviewDialogCancel() {
      this.previewDialogVisible = false
    },
    loadTables() {
      // 查询表数据
      this.tableGridLoading = true
      // CodeDesignApi.getTables({}).then(res => {
      //   this.tableGridLoading = false
      //   this.tables = response.data.items
      // })
      const actionUrl = this.HOST + '/codedesign' + '/tables'
      axios({
        url: actionUrl,
        method: 'post',
        params: {}
      }).then(response => {
        console.log('response')
        console.log(response)
        this.tableGridLoading = false
        this.tables = response.data.data.items
      })
    },
    onOpenTable(reload) {
      // 弹出表模态窗口
      this.tableDialogVisible = true
      if (reload === true || this.tables.lenght === 0) {
        this.loadTables()
      }
    },
    onSelectTable(row) {
      // 选中表事件
      this.tableDialogVisible = false
      this.table = JSON.parse(JSON.stringify(row))
      this.sTables.push(row)
    },
    onPreviewClick() {
      // 弹预览代码参数窗口
      if (this.table && this.table.name) {
        // this.previewDialogVisible = true
        // 不弹出窗口直接生成代码
        this.onPreviewDialogConfirm()
      }
    },
    timeFormate(timeStamp) {
      const year = new Date(timeStamp).getFullYear()
      const month = new Date(timeStamp).getMonth() + 1 < 10 ? '0' + (new Date(timeStamp).getMonth() + 1) : new Date(timeStamp).getMonth() + 1
      const date = new Date(timeStamp).getDate() < 10 ? '0' + new Date(timeStamp).getDate() : new Date(timeStamp).getDate()
      const hh = new Date(timeStamp).getHours() < 10 ? '0' + new Date(timeStamp).getHours() : new Date(timeStamp).getHours()
      const mm = new Date(timeStamp).getMinutes() < 10 ? '0' + new Date(timeStamp).getMinutes() : new Date(timeStamp).getMinutes()
      const ss = new Date(timeStamp).getSeconds() < 10 ? '0' + new Date(timeStamp).getSeconds() : new Date(timeStamp).getSeconds()
      this.day = year + '年' + month + '月' + date + '日' + '_' + hh + ':' + mm + ':' + ss
    },
    onExportClick() {
      // 弹预览代码参数窗口
      if (this.table && this.table.name) {
        this.timeFormate(new Date())
        // location.href = 'codedesign/exportCode?tableName=' + this.table.name + '&moduleName=' + this.table.moduleName
        // CodeDesignApi.exportCode(this.table).then(response => {
        //   if (response.status === 200) {
        //     const blob = response.data
        //     const reader = new FileReader()
        //     reader.readAsDataURL(blob)
        //     reader.onload = (e) => {
        //       const a = document.createElement('a')
        //       a.download = 'code-' + this.day + '.zip'
        //       a.href = e.target.result
        //       document.body.appendChild(a)
        //       a.click()
        //       document.body.removeChild(a)
        //     }
        //   }
        // })
        const actionUrl = this.HOST + '/codedesign' + '/exportCode'
        // debugger
        axios({
          url: actionUrl,
          method: 'post',
          data: this.table,
          responseType: 'blob'
        }).then(response => {
          console.log('response')
          console.log(response)
          const blob = response.data
          const reader = new FileReader()
          reader.readAsDataURL(blob)
          // 下载，取消
        })
      }
    },
    onRemoveClick(index) {
      this.sTables.splice(index, 1)
    },
    onExportsClick() {
      // 弹预览代码参数窗口
      if (this.sTables && this.sTables[0]) {
        this.timeFormate(new Date())
        // CodeDesignApi.exportsCode(JSON.stringify(this.sTables)).then(response => {
        //   if (response.status === 200) {
        //     const blob = response.data
        //     const reader = new FileReader()
        //     reader.readAsDataURL(blob)
        //     reader.onload = (e) => {
        //       const a = document.createElement('a')
        //       a.download = 'code-' + this.day + '.zip'
        //       a.href = e.target.result
        //       document.body.appendChild(a)
        //       a.click()
        //       document.body.removeChild(a)
        //     }
        //   }
        // })
        const actionUrl = this.HOST + '/codedesign' + '/exportsCode'

        axios({
          url: actionUrl,
          method: 'post',
          headers: {
            'Content-Type': 'application/json'
          },
          data: JSON.stringify(this.sTables),
          responseType: 'blob'
        }).then(response => {
          console.log('response')
          console.log(response)
          const blob = response.data
          const reader = new FileReader()
          reader.readAsDataURL(blob)
          // reader.onload = (e) => {
          //   const a = document.createElement('a')
          //   a.download = 'code-' + this.day + '.zip'
          //   a.href = e.target.result
          //   document.body.appendChild(a)
          //   a.click()
          //   document.body.removeChild(a)
          // }
        })
      }
    },
    handleCopy(text, event) {
      clip(text, event)
    }
  }
}
</script>
